/*
 * Copyright (C) 2021 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.dona.imsidetector.Dialog.Freq;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.dona.imsidetector.R;
import com.dona.imsidetector.db.dao.FreqDao;
import com.dona.imsidetector.db.entity.Frequency;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SelectFreqDialog extends AlertDialog {

    private static final String TAG = "MyDialog";
    // 在构造方法里提前加载了样式
    private Context context;
    private int layoutResId; // 布局文件id
    private TextView title;
    private Button positiveBtn;
    private Button negativeBtn;
//    private Button addFreqBtn;
    // 设备1
    private RecyclerView lrecyclerView;
    private List<Frequency> lfrequencyList = new ArrayList<>();
    private Set<Integer> lselected = new HashSet<>();
    private IHCallback lihCallback;
    private ItemTouchHelper llitemTouchHelper;
    private FreqSelectAdapter ladapter;

    // 设备2
    private RecyclerView rrecyclerView;
    private List<Frequency> rfrequencyList = new ArrayList<>();
    private Set<Integer> rselected = new HashSet<>();
    private IHCallback rihCallback;
    private ItemTouchHelper rlitemTouchHelper;

    private PositiveListener positiveListener;
    private FreqSelectAdapter radapter;


    public SelectFreqDialog(@NonNull Context context, int layoutResId, int themeResId) {
        super(context,themeResId);
        this.context = context;
        this.layoutResId = layoutResId;
    }

//    public void setSelected(Set<Integer> selected) {
//        this.lselected = selected;
//    }
//
//    public Set<Integer> getSelected() {
//        return lselected;
//    }
//
//    public void setFrequencyList(List<Frequency> frequencyList) {
//        this.lfrequencyList = frequencyList;
//    }
//
//    public List<Frequency> getFrequencyList() {
//        return lfrequencyList;
//    }
//
//    public FreqSelectAdapter getAdapter(){
//        return ladapter;
//    }


    public FreqSelectAdapter getRadapter() {
        return radapter;
    }





    public List<Frequency> getLfrequencyList() {
        return lfrequencyList;
    }

    public void setLfrequencyList(List<Frequency> lfrequencyList) {
        this.lfrequencyList = lfrequencyList;
    }

    public Set<Integer> getLselected() {
        return lselected;
    }

    public void setLselected(Set<Integer> lselected) {
        this.lselected = lselected;
    }

    public FreqSelectAdapter getLadapter() {
        return ladapter;
    }



    public List<Frequency> getRfrequencyList() {
        return rfrequencyList;
    }

    public void setRfrequencyList(List<Frequency> rfrequencyList) {
        this.rfrequencyList = rfrequencyList;
    }

    public Set<Integer> getRselected() {
        return rselected;
    }

    public void setRselected(Set<Integer> rselected) {
        this.rselected = rselected;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 提前设置Dialog的一些样式
        Window dialogWindow = getWindow();
        dialogWindow.setGravity(Gravity.CENTER); //设置dialog显示居中

        setContentView(layoutResId);
//        WindowManager windowManager = ((Activity) context).getWindowManager();
//        Display defaultDisplay = windowManager.getDefaultDisplay();
//        WindowManager.LayoutParams lp = getWindow().getAttributes();
//        lp.width = defaultDisplay.getWidth() * 4/5; //设置dialog宽度为屏幕的4/5
//        getWindow().setAttributes(lp);
        setCanceledOnTouchOutside(true); // 点击外部Dialog消失

        initView();
        initListener();
    }

    public interface PositiveListener {
        void onClick(Set<Integer> selectLFreqs,Set<Integer> selectRFreqs);
    }

    public void setOnPositiveListener(PositiveListener positiveListener){
        this.positiveListener = positiveListener;
    }




    private void initListener() {

        positiveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                positiveListener.onClick(lselected,rselected);
            }
        });


        negativeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });



    }

    private void initView() {
        title = (TextView) getWindow().findViewById(R.id.title);
        positiveBtn = (Button) getWindow().findViewById(R.id.positive);
        negativeBtn = (Button) getWindow().findViewById(R.id.negative);

        // 设备1
        lrecyclerView = (RecyclerView) getWindow().findViewById(R.id.leftRecyclerView);
        lrecyclerView.setLayoutManager(new LinearLayoutManager(context));
        ladapter = new FreqSelectAdapter(context, lfrequencyList,lselected,0);

        lihCallback = new IHCallback(ladapter);
        lrecyclerView.setAdapter(ladapter);
        llitemTouchHelper = new ItemTouchHelper(lihCallback);
        llitemTouchHelper.attachToRecyclerView(lrecyclerView);

        // 设备2
        rrecyclerView = (RecyclerView) getWindow().findViewById(R.id.rightRecyclerView);
        rrecyclerView.setLayoutManager(new LinearLayoutManager(context));
        radapter = new FreqSelectAdapter(context, rfrequencyList,rselected, 1);

        rihCallback = new IHCallback(radapter);
        rrecyclerView.setAdapter(radapter);
        rlitemTouchHelper = new ItemTouchHelper(rihCallback);
        rlitemTouchHelper.attachToRecyclerView(rrecyclerView);

    }



    public class FreqSelectAdapter extends RecyclerView.Adapter<FreqSelectViewHolder> implements IOperationData {

        private List<Frequency> frequencyList = new ArrayList<>();
        private Context context;
        private Set<Integer> selectedFreqs = new HashSet<>();
        private  Integer device;

        public FreqSelectAdapter(Context context, List<Frequency> frequencyList, Set<Integer> selectedFreqs, Integer device) {
            this.context = context;
            this.frequencyList = frequencyList;
            this.selectedFreqs = selectedFreqs;
            this.device = device;
        }

        @NonNull
        @Override
        public FreqSelectViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(context);
            View view = inflater.inflate(R.layout.adapter_freq_select_listitem, parent, false);
            FreqSelectViewHolder viewHolder = new FreqSelectViewHolder(view,selectedFreqs,device);

            viewHolder.setIsRecyclable(false);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull FreqSelectViewHolder holder, int position) {
            Frequency frequency = frequencyList.get(position);

            holder.bind(frequency);

        }

        @Override
        public int getItemCount() {
            return frequencyList.size();
        }

        @Override
        public void onItemMove(int fromPosition, int toPosition) {
            Collections.swap(frequencyList, fromPosition, toPosition);
            notifyItemMoved(fromPosition, toPosition);
        }

        @Override
        public void onItemDismiss(int position) {
            FreqDao.delete(frequencyList.remove(position));

            notifyItemRemoved(position);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
//        WindowManager.LayoutParams attributes = this.getWindow().getAttributes();
//        Log.e(TAG, "onStart: " + attributes.width);
//        attributes.width = 1000;
//        attributes.height = 800;
//        this.getWindow().setAttributes(attributes);
    }

    private class FreqSelectViewHolder extends RecyclerView.ViewHolder {

        private CheckBox selectCb;
        private TextView frequency;
        private TextView isp;
        private TextView span;
        private Frequency bindFreq;
        private Set<Integer> selectedFreqs;
        private View itemView;
        private Integer device;

        public FreqSelectViewHolder(@NonNull View itemView, Set<Integer> selected, Integer device) {
            super(itemView);
            this.selectedFreqs = selected;
            this.device = device;
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dealSelect();
                }
            });
            this.itemView = itemView;
            selectCb = (CheckBox) itemView.findViewById(R.id.checkbox);

            selectCb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dealSelect();

                }
            });
            frequency = (TextView) itemView.findViewById(R.id.frequency);
            isp = (TextView) itemView.findViewById(R.id.isp);
            span = (TextView) itemView.findViewById(R.id.span);
        }

        public void bind(Frequency frequency) {
            this.bindFreq = frequency;
            this.selectCb.setChecked(selectedFreqs.contains(frequency.getFreq()));
            this.frequency.setText(frequency.getFreq().toString());
            this.isp.setText(frequency.getIspDesc());
            this.span.setText(frequency.getBand());
        }

        private void dealSelect(){
            if (!selectedFreqs.contains(bindFreq.getFreq())) {
                if(device == 0 && selectedFreqs.size() > 0 ){
                    Integer one = selectedFreqs.iterator().next();
                    for(int i = 0; i < lfrequencyList.size(); i++){
                        Frequency frequency = lfrequencyList.get(i);
                        if(frequency.getFreq().equals(one)){

                            if(!frequency.getBand().equals(bindFreq.getBand())){
                                Log.e(TAG, "selectCb onClick: " + frequency + " bindfreq:" + bindFreq);
                                selectCb.setChecked(false);
//                                        XToast.info(context,"已经选择了频段"+ frequency.getBand() + "请勿再选择" + bindFreq.getBand());
                                return;
                            }
                        }
                    }
                }
                selectedFreqs.add(bindFreq.getFreq());
                selectCb.setChecked(true);
            } else {
                selectedFreqs.remove(bindFreq.getFreq());
                selectCb.setChecked(false);
            }
            Log.e("FreqSelectViewHolder", "selected: " + selectedFreqs.toString());
        }
    }



}
